<?php

namespace july\julyadmin\builder\forms;

use july\julyadmin\builder\FormBase;
use \july\julyadmin\common\model\Config;

/**
 * 表单EditorMd组件
 */
class EditorMd extends FormBase
{
    /**
     * 添加组件
     * @Author
     * @DateTime 2023-07-16T12:14:26+0800
     * @param    string                   $field 字段
     * @param    string                   $label 名称
     * @return this
     */
    public function __construct($field = '', $label = '')
    {
        $form              = new \stdClass();
        $form->type        = 'editor-md';
        $form->field       = $field;
        $form->label       = $label;
        $form->placeholder = $label;
        $form->help        = '';
        $form->tips        = ['tips' => '', 'direction' => 2, 'time' => 0, 'background' => '#000000'];
        $form->required    = false;
        $form->width       = '100%';
        $form->height      = '400px';
        $form->ext         = [];
        $form->showToolbar = 'true';
        $form->preview     = 'true';

        //内容
        $form->value   = '';
        $form->default = '';
        $this->form    = $form;

        $this->js = '
            <script type="text/javascript" src="/static/assets/admin/js/editor.md/editormd.min.js"></script>
            <script type="text/javascript" src="/static/assets/admin/js/editor.md/lib/marked.min.js"></script>
            <script type="text/javascript" src="/static/assets/admin/js/editor.md/lib/prettify.min.js"></script>
            <script type="text/javascript" src="/static/assets/admin/js/editor.md/lib/raphael.min.js"></script>
            <script type="text/javascript" src="/static/assets/admin/js/editor.md/lib/underscore.min.js"></script>
            <script type="text/javascript" src="/static/assets/admin/js/editor.md/lib/sequence-diagram.min.js"></script>
            <script type="text/javascript" src="/static/assets/admin/js/editor.md/lib/flowchart.min.js"></script>
            <script type="text/javascript" src="/static/assets/admin/js/editor.md/lib/jquery.flowchart.min.js"></script>
        ';
        $this->css = '

        <link rel="stylesheet" type="text/css" href="/static/assets/admin/js/editor.md/css/editormd.min.css" />

        ';
        return $this;
    }

    /**
     * 设置编辑器宽度
     * @Author
     * @DateTime 2023-07-16T12:40:37+0800
     * @param    string                   $width 宽度，可以是具体px值也可以是百分比
     * @return this
     */
    public function width($width = '100%')
    {
        $this->form->width = $width;
        return $this;
    }

    /**
     * 设置编辑器高度
     * @Author
     * @DateTime 2023-07-16T12:41:10+0800
     * @param    string                   $height 高度，可以是具体px值也可以是百分比，也可是是auto，自动高度
     * @return this
     */
    public function height($height = '400px')
    {
        $this->form->height = $height;
        return $this;
    }

    /**
     * 设置允许上传格式，如jpg,png
     * @Author   July
     * @DateTime 2023-10-23T17:38:30+0800
     * @param    array                   $ext 文件格式['jpg','png']
     */
    public function setExt($ext = [])
    {
        if (!is_array($ext)) {
            throw new \Exception("参数ext必须是一维数组，如：['jpg','png']");
        }
        $this->form->ext = $ext;
        return $this;
    }

    /**
     * 显示工具栏
     * @Author   July
     * @DateTime 2024-01-24T20:42:23+0800
     * @return   this
     */
    public function showToolbar()
    {
        $this->form->showToolbar = 'true';
        return $this;
    }

    /**
     * 隐藏工具栏
     * @Author   July
     * @DateTime 2024-01-24T20:43:24+0800
     * @return   this
     */
    public function hideToolbar()
    {
        $this->form->showToolbar = 'false';
        return $this;
    }

    /**
     * 是否打开实时预览
     * @Author   July
     * @DateTime 2024-01-24T20:43:24+0800
     * @param    boolean    $open     是否打开实时预览，true|false
     * @return   this
     */
    public function openPreview($open = true)
    {
        $this->form->preview = $open === true ? 'true' : 'false';
        return $this;
    }

    /**
     * 渲染组件
     * @Author
     * @DateTime 2023-07-16T12:22:46+0800
     * @return   array
     */
    public function render()
    {
        $this->form->value = $this->form->default;
        if (isset($this->data[$this->form->field]) && $this->data[$this->form->field] !== "") {
            $this->form->value = $this->data[$this->form->field];
        }

        $required_html = $this->form->required && !$this->isView ? ' <font style="color:red;font-weight:bold;font-size:20px;vertical-align:-webkit-baseline-middle;">*</font>' : '';

        //处理tips
        $tips = '';
        if ($this->form->tips['tips']) {
            $tips = '<font class="form-tips-icon"><i class="mdi mdi-information-outline" tips="' . $this->form->tips['tips'] . '" direction="' . $this->form->tips['direction'] . '" time="' . $this->form->tips['time'] . '" background="' . $this->form->tips['background'] . '" onclick="showTips(this)"></i></font>';
        }

        $this->html .= <<< EOT

        <div class="row ps-0 pe-0 ms-0 me-0 mt-3 mb-3 col-md-{$this->colWidth}">
            <label class="col-sm-{$this->labelWidth} col-form-label pe-2 col-form-label-sm text-sm-end text-md-end text-lg-end text-xl-end">
                {$tips}{$this->form->label}
                {$required_html}
            </label>
EOT;
        $input_html = "";
        $input_html .= '<div id="form-' . $this->form->field . '-box">';
        if ($this->isView) {
            $input_html .= $this->form->value !== '' ? $this->form->value : '空';
        } else {
            $input_html .= '<textarea id="form-' . $this->form->field . '" name="' . $this->form->field . '" ' . ($this->form->required ? ' required' : '') . ' style="width:' . $this->form->width . ';" ' . $this->readonly . '>' . $this->form->value . '</textarea>';
        }

        $input_html .= '</div>';
        $input_html .= '<div class="error-box"></div>';

        //处理help
        if ($this->form->help) {
            $input_html .= <<<EOT

            <div class="form-help form-text">
                <i class="mdi mdi-information-outline"></i>
                <font>{$this->form->help}</font>
            </div>
EOT;
        }

        $this->html .= <<< EOT

            <div class="col-sm-{$this->inputWidth}">
                {$input_html}
            </div>
        </div>
EOT;
        if (!$this->isView) {
            $app_map = config('app.app_map', []);
            $module  = 'admin';
            if ($app_map) {
                if ($key = array_search($module, $app_map)) {
                    $module = $key;
                }
            }
            $serverUrl = url('/' . $module . '/Ueditor/Index');
            $uploadUrl = url('/' . $module . '/Files/commonUploadForm');
            $md5       = md5($this->form->field);
            $readonly  = $this->readonly ? 'true' : 'false';
            $size      = Config::config('ImageUpload.imageMaxSize');
            if ($this->form->ext) {
                $exts = $this->form->ext;
            } else {
                $exts = array_filter(explode(',', Config::config('ImageUpload.imageAllowImages')));
            }
            $ext = [];
            foreach ($exts as $ext_k => $ext_v) {
                $ext[] = "'{$ext_v}'";
            }
            $ext          = implode(',', $ext);
            $this->script = <<<EOT

            <script type="text/javascript">
            if({$readonly}==true){
                var {$this->form->field}_editormd = editormd.markdownToHTML('form-{$this->form->field}-box', {
                    htmlDecode : "style,script,iframe",
                    path: "/static/assets/admin/js/editor.md/lib/",
                    emoji : true,
                    taskList : true,
                    tex : true,  // 默认不解析
                    flowChart : true,  // 默认不解析
                    sequenceDiagram : true,  // 默认不解析
                });
            }else{
                var {$this->form->field}_editormd = editormd('form-{$this->form->field}-box', {
                    width  : '{$this->form->width}',
                    height : '{$this->form->height}',
                    autoHeight:'{$this->form->height}'=='auto'?true:false,
                    path: "/static/assets/admin/js/editor.md/lib/",
                    codeFold : true,
                    htmlDecode : 'iframe|on*', // 开启标签
                    imageUpload : true,
                    emoji:true,
                    imageUploadURL : '{$uploadUrl}',
                    uploadImageCallback:'uploadImageCallback_{$md5}',
                    readonly:{$readonly},
                    imageFormats : [$ext],
                    toolbar:{$this->form->showToolbar},
                    onload : function() {
                        if({$this->form->preview}==true){
                            this.watch();
                        }else{
                            this.unwatch();
                        }
                    }
                });
            }
            </script>
EOT;
        }

        $result = ['html' => $this->html, 'script' => $this->script, 'js' => $this->js, 'css' => $this->css];
        return $result;
    }
}
